﻿using FlyingEye.HttpServices;
using FlyingEyeAdmin.Shell;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace FlyingEye
{
    /// <summary>
    /// LoginWindow.xaml 的交互逻辑
    /// </summary>
    public partial class LoginWindow : Window
    {
        private readonly HttpTokenManager _tokenManager;
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<LoginWindow> _logger;
        private readonly IOptions<HttpClientServiceOptions> _options;

        public LoginWindow(HttpTokenManager httpTokenManager,
            IOptions<HttpClientServiceOptions> options, 
            ILogger<LoginWindow> logger, 
            IServiceProvider serviceProvider)
        {
            _options = options;
            _tokenManager = httpTokenManager;
            _logger = logger;
            _serviceProvider = serviceProvider;
            InitializeComponent();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            var password = this.PasswordTextBox.Password;
            var userName = this.UserNameTextBox.Text;

            if (string.IsNullOrWhiteSpace(password) || password.Length < 6)
            {
                MessageBox.Show("密码长度必须大于等于6。");
                return;
            }

            if (string.IsNullOrWhiteSpace(password) || password.Length < 5)
            {
                MessageBox.Show("用户名长度必须大于等于5。");
                return;
            }

            try
            {
                _options.Value.Password = password;
                _options.Value.UserName = userName;

                await _tokenManager.GetBearerTokenAsync();

                this.DialogResult = true;
                this.Close();
            }
            catch(Exception ex)
            {
                _logger.LogError(ex, "登录失败。");
                MessageBox.Show("登录失败。");
            }
        }
    }
}
